#include "UrlIconProvider.h"

#include <QSettings>
#include <QPixmap>

UrlIconProvider::UrlIconProvider()
{
    m_defaultSecureIcon = QIcon(QLatin1String(":icons/lock.png"));
    m_defaultIcon = QIcon(QLatin1String(":defaulticon.png"));
}

QIcon UrlIconProvider::icon(const QUrl &url) const
{
    if (url.scheme() == QLatin1String("https"))
    {
       if (m_defaultSecureIcon.isNull())
           m_defaultSecureIcon = QIcon(QLatin1String(":icons/lock.png"));

        return m_defaultSecureIcon.pixmap(24,24);
    }

   if (!url.host().isEmpty())
   {
       QString host = url.host();
       QIcon icon /*= getHostIcon(host)*/;
       if (!icon.isNull())
           return icon;

       {
           QSettings settings("cache/Icons", QSettings::IniFormat);
           settings.beginGroup(QLatin1String("Icons"));
           QPixmap pix;
           QByteArray image = settings.value( host ).toByteArray();
           settings.endGroup();
           if (pix.loadFromData(image, "PNG"))
               if (!pix.isNull())
                   return QIcon(pix).pixmap(24,24);
       }

   }

   if (m_defaultIcon .isNull())
       m_defaultIcon = QIcon(QLatin1String(":defaulticon.png"));

   return m_defaultIcon.pixmap(24, 24);
}

void UrlIconProvider::CheckIcon(const QUrl &url)
{
    if (url.isEmpty())
        return;

    QString host = url.host();
    QIcon icon /*= getHostIcon( host )*/;
    if ( icon.isNull() && !host.isEmpty())
    {
        QSettings settings("cache/Icons", QSettings::IniFormat);
        settings.beginGroup(QLatin1String("Icons"));
        QPixmap pix;
        QByteArray image = settings.value( host ).toByteArray();
        settings.endGroup();
        pix.loadFromData( image, "PNG" );
        if (!pix.isNull())
            return;

        QUrl iconUrl = url.scheme() + "://" + host + "/favicon.ico";
//        QNetworkRequest request(iconUrl);
//        m_iconManager.get(request);
    }
}
